package com.weshare.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.weshare.model.FileCustom;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class FileBackupJob implements SimpleJob {

    private final int FETCH_SIZE = 1;
    public static List<FileCustom> files = new ArrayList<FileCustom>();

    static {
        for (int i = 0; i < 11; i++) {
            FileBackupJob.files.add(new FileCustom(String.valueOf(i + 10), "文件" + (i + 10), "text", "content" + (i + 10)));
            FileBackupJob.files.add(new FileCustom(String.valueOf(i + 20), "文件" + (i + 20), "image", "content" + (i + 20)));
            FileBackupJob.files.add(new FileCustom(String.valueOf(i + 30), "文件" + (i + 30), "radio", "content" + (i + 30)));
            FileBackupJob.files.add(new FileCustom(String.valueOf(i + 40), "文件" + (i + 40), "vedio", "content" + (i + 40)));
        }
    }

    public void execute(ShardingContext shardingContext) {

        // 作业分片信息
        int shardingItem = shardingContext.getShardingItem();
        System.out.println(String.format("作业分片：%d", shardingItem));
        //分片参数
        String jobParameter = shardingContext.getShardingParameter();
        System.out.println(jobParameter);
        // 获取备份文件
        List<FileCustom> fileCustoms = fetehUnBackupFiles(FETCH_SIZE);
        // 备份文件
        backupFiles(fileCustoms);
    }

    /**
     * 备份文件
     *
     * @param files
     */
    private void backupFiles(List<FileCustom> files) {
        for (FileCustom fileCustom : files) {

            fileCustom.setBackedUp(true);
            System.out.printf("time:%s,备份文件，名称：%s，类型：%s\n", LocalDateTime.now(), fileCustom.getName(), fileCustom.getType());
        }
    }

    /**
     * 获取备份文件
     *
     * @param count
     * @return
     */
    private List<FileCustom> fetehUnBackupFiles(int count) {
        List<FileCustom> fetchList = new ArrayList<FileCustom>();
        int num = 0;
        for (FileCustom fileCustom : files) {
            if (num >= count) {
                break;
            }
            if (!fileCustom.getBackedUp()) {
                fetchList.add(fileCustom);
                num++;
            }
        }
        System.out.printf("time:%s,获取文件%d个\n", LocalDateTime.now(), num);
        return fetchList;
    }
}
